package com.central.apps.service.impl;

import com.central.app.service.HandlerService;
import com.central.apps.dao.PmDao;
import com.central.apps.entity.*;
import com.central.apps.service.CommonService;
import com.central.apps.service.PmService;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class PmServiceImpl implements PmService {
    @Autowired
    PmDao PmDao;

    @Autowired private HandlerService handlerService;
    @Autowired private CommonService CommonService;

    @Override
    @Transactional
    public void updateNextTime(int id, String nextDate,String lostDate) {
        PmDao.updateNextTime(id,nextDate,lostDate);
    }

    @Override

    public void queryInspectionPlan(String PlanType) throws Exception {

        List<BlPm> pmlist = PmDao.queryPm();

        for (BlPm blpm : pmlist) {
            PmCreateWorkorder(blpm);
        }



    }





    @Override
    public String getNextexDate(Date exDate,String frequency,String cycle){

        int fre = Integer.parseInt(frequency);
        int unitTime = 0;
        if("D".equals(cycle)){
            unitTime = 1;
        }
        if("W".equals(cycle)){
            unitTime = 7;
        }
        if("M".equals(cycle)){
            unitTime = 30;
        }
        if("Y".equals(cycle)){
            unitTime = 365;
        }

        Calendar ca = Calendar.getInstance();
        ca.setTime(exDate);
        ca.add(Calendar.DAY_OF_MONTH, fre*unitTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        return sdf.format(ca.getTime());
    }

    @Override
    public String quryMaxWonum(String woType, String woFax) {
        String nowWonum = PmDao.quryMaxWonum(woType);
        if("".equals(nowWonum) || nowWonum==null){
            nowWonum =  "100000";
        }else{
            nowWonum = String.format("%06d",
                    new Object[] {
                            Integer.valueOf(Integer.parseInt(nowWonum.substring(nowWonum.length() - 6)) + 1) });
        }
        nowWonum = woFax + nowWonum;

        return nowWonum;
    }

    @Override
    public List<BlInsparealocation> quryLocationList(String insaenum) {
        return PmDao.quryLocationList(insaenum);
    }

    @Override
    public void insertWoLocation(String wonum, String location, String desc) {
        PmDao.insertWoLocation(wonum,location,desc);
    }

    @Override
    public List<BlInsparealine> queryAssetList(String insaenum) {
        return PmDao.queryAssetList(insaenum);
    }

    @Override
    public void insertWoAsset(String wonum, String assetnum, String desc) {
        PmDao.insertWoAsset(wonum,assetnum,desc);
    }

    @Override
    public List<BlInspectionstandardline> quryTaskList(String insaenum) {
        return PmDao.quryTaskList(insaenum);
    }

    @Override
    public void insertWoTask(String wonum, BlInspectionstandardline task) {
        PmDao.insertWoTask(wonum,task);
    }

    @Override
    public Map<String, Object> getActiveMap(BlPm blpm) {
        Map<String,Object> ActiveMap = new HashMap<>();
        ActiveMap.put("1",blpm.getZ1());
        ActiveMap.put("2",blpm.getZ2());
        ActiveMap.put("3",blpm.getZ3());
        ActiveMap.put("4",blpm.getZ4());
        ActiveMap.put("5",blpm.getZ5());
        ActiveMap.put("6",blpm.getZ6());
        ActiveMap.put("7",blpm.getZ7());

        return ActiveMap;
    }



    @Override
    public void getRouteGenWorkorder(String RouteNum,String MaxWonum,String woDesc,String insaenum,BlPm blpm) {



        String routeSql = "select isparentwo from bl_insparea where insaenum='"+RouteNum+"'";
        List<Map<String, Object>> getRouteLists = handlerService.findBySql(routeSql);
        if(getRouteLists.size()>0){

            Map Route = getRouteLists.get(0);
            String isparentwo = (String) Route.get("isparentwo");
            
            if ("1".equals(isparentwo)){
                genParentWorkorder(RouteNum,MaxWonum,woDesc,insaenum,blpm);
            }else{
                genManyAssetWorkorder(RouteNum, MaxWonum,insaenum);
            }


        }

    }



    @Override
    public void genManyAssetWorkorder(String RouteNum,String MaxWonum,String insaenum) {
        List<BlInsparealocation> blInspectlocation = null;
        List<BlInsparealine> BlInspectasset = null;
        blInspectlocation = quryLocationList(RouteNum);

        genTaskByInsaenum(MaxWonum,insaenum);

        for (BlInsparealocation inspectlocation : blInspectlocation) {
            insertWoLocation(MaxWonum,inspectlocation.getSeat(),inspectlocation.getLocaEnityDescription());
        }
        BlInspectasset = queryAssetList(RouteNum);
        for (BlInsparealine blInspectasset : BlInspectasset) {
            insertWoAsset(MaxWonum,blInspectasset.getInsaeassetnum(),blInspectasset.getAssetEnityDescription());
        }
    }

    @Override
    public void genParentWorkorder(String RouteNum,String parentWoNum,String woDesc,String insaenum,BlPm blpm) {


        List<BlInsparealocation> blInspectlocation = null;
        List<BlInsparealine> BlInspectasset = null;


        String insertWoSql = "";

        int woseq = 0;
        String woafterSeq = "";
        blInspectlocation = quryLocationList(RouteNum);
        for (BlInsparealocation inspectlocation : blInspectlocation) {


            woseq += 1;

            if(woseq>10){
                woafterSeq = "-0"+woseq;
            }else{
                woafterSeq = "-00"+woseq;
            }
            if(woseq>100){
                woafterSeq = "-"+woseq;
            }
            genTaskByInsaenum(parentWoNum+woafterSeq,insaenum);
            insertWoSql = "insert into bl_workorder (wonum,description,createuser,updatetime,createtime,udwotype,status,location,locationdesc,parentwo,parentwodesc,orgcode,sitecode,deptcode,maintenanceprincipal,wxfzrname,classcode,classdesc,fixplannum,fixplandesc,inspareacode,inspareadesc,plannum,plandescription)values('"+parentWoNum+woafterSeq+"','"+woDesc+"-"+inspectlocation.getLocaEnityDescription()+"',1,now(),now(),'PM工单','草稿','"+inspectlocation.getSeat()+"','"+inspectlocation.getLocaEnityDescription()+"','"+parentWoNum+"','"+woDesc+"','"+blpm.getOrgcode()+"','"+blpm.getSitecode()+"','"+blpm.getDeptcode()+"','"+blpm.getPerson()+"','"+blpm.getFzrdesc()+"','"+blpm.getClasscode()+"','"+blpm.getClassdesc()+"','"+blpm.getInspectionplan()+"','"+blpm.getInspectionplandesc()+"','"+blpm.getLinerepair()+"','"+blpm.getLinerepairdesc()+"','"+blpm.getPmnum()+"','"+blpm.getDescription()+"')";

            handlerService.updateBySql(insertWoSql);

        }
        BlInspectasset = queryAssetList(RouteNum);
        for (BlInsparealine blInspectasset : BlInspectasset) {

            woseq += 1;

            if(woseq>10){
                woafterSeq = "-0"+woseq;
            }else{
                woafterSeq = "-00"+woseq;
            }
            if(woseq>100){
                woafterSeq = "-"+woseq;
            }
            genTaskByInsaenum(parentWoNum+woafterSeq,insaenum);
            insertWoSql = "insert into bl_workorder (wonum,description,createuser,updatetime,createtime,udwotype,status,assetnum,assetdesc,parentwo,parentwodesc,orgcode,sitecode,deptcode,maintenanceprincipal,wxfzrname,classcode,classdesc,fixplannum,fixplandesc,inspareacode,inspareadesc,plannum,plandescription)values('"+parentWoNum+woafterSeq+"','"+woDesc+"-"+blInspectasset.getAssetEnityDescription()+"',1,now(),now(),'PM工单','草稿','"+blInspectasset.getInsaeassetnum()+"','"+blInspectasset.getAssetEnityDescription()+"','"+parentWoNum+"','"+woDesc+"','"+blpm.getOrgcode()+"','"+blpm.getSitecode()+"','"+blpm.getDeptcode()+"','"+blpm.getPerson()+"','"+blpm.getFzrdesc()+"','"+blpm.getClasscode()+"','"+blpm.getClassdesc()+"','"+blpm.getInspectionplan()+"','"+blpm.getInspectionplandesc()+"','"+blpm.getLinerepair()+"','"+blpm.getLinerepairdesc()+"','"+blpm.getPmnum()+"','"+blpm.getDescription()+"')";
            handlerService.updateBySql(insertWoSql);

        }
    }

    @Override
    public void genTaskByInsaenum(String wonum,String insaenum) {
        String getInfosSql ="select * from bl_jobtask where jpnum ='"+insaenum+"'";
        List<Map<String, Object>> getTaskLists = handlerService.findBySql(getInfosSql);

        String insertPmTaskSql = "";

        for (Map<String, Object> taskList : getTaskLists) {
            insertPmTaskSql = "insert into bl_workordertask(inspectionassetnum,inspectioncontent,wonum)values ('"+taskList.get("step")+"','"+taskList.get("workmethod")+"','"+wonum+"')";
            handlerService.updateBySql(insertPmTaskSql);

        }

        String getWpmaterialSql ="select * from bl_wpmaterial where JOBPLANID ='"+insaenum+"'";
        List<Map<String, Object>> getWpmaterialLists = handlerService.findBySql(getWpmaterialSql);
        log.info("====================="+getWpmaterialLists.size());
        String insertPmwpmaterialSql = "";
        for (Map<String, Object> wpmaterialList : getWpmaterialLists) {
            insertPmwpmaterialSql = "insert into bl_wpmaterial(itemnum,materialEnity_DESCRIPTION,itemqty,wonum)values ('"+wpmaterialList.get("ITEMNUM")+"','"+wpmaterialList.get("DESCRIPTION")+"',"+wpmaterialList.get("ITEMQTY")+",'"+wonum+"')";



            handlerService.updateBySql(insertPmwpmaterialSql);
        }
        String getWplaborSql ="select * from bl_wplabor where JOBPLANID ='"+insaenum+"'";
        List<Map<String, Object>> getWplaborLists = handlerService.findBySql(getWplaborSql);
        String insertPmWplaborSql = "";
        for (Map<String, Object> WplaborList : getWplaborLists) {
            insertPmWplaborSql = "insert into bl_wplabor(LABORCODE,planUserEnity_DISPLAYNAME,craftdesc,wonum)values('"+WplaborList.get("LABORCODE")+"','"+WplaborList.get("planUserEnity_DISPLAYNAME")+"','"+WplaborList.get("craftdesc")+"','"+wonum+"')";
            handlerService.updateBySql(insertPmWplaborSql);
        }
    }


    @Override
    public String PmCreateWorkorder(BlPm blpm) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        BlWorkorder BlWorkorder = new BlWorkorder();

        List<BlInsparealocation> blInspectlocation = null;
        List<BlInsparealine> BlInspectasset = null;
        List<BlInspectionstandardline> BlInspectionstandardline = null;

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();


        String isaction =  blpm.getIsaction();
        if(isaction.equals("0")){
            json.put("code", "1");
            json.put("msg", "当前PM未启动！");
            return json.toJSONString();
        }

        //下次执行时间
        Date nextDate = null;
        Date sysDate = new Date();
        // 周期
        String cycle = "";
        // 频率
        int frequency = 0;
        //最大的工单编号
        String MaxWonum = "";
        // 当前生成的工单ID
        int workorderid = 0;

        String qyNum = "";
        String BZNum = "";
        //计算过后的下次生成日期;
        String upDateNextDate = "";

        // 是否是提前生成
        boolean isBefore = false;
        // 是否启用周期设置
        boolean isZQActive = true;

            MaxWonum = "";
            nextDate = blpm.getNextexecutetime();



             Map<String, Object> week = getActiveMap(blpm);



            String isStrBefore = blpm.getIsbefore();
            if(isStrBefore.equals("1")){
                isBefore = true;
            }



            Date endExentDate = nextDate;
            // 周期性设置


            if(blpm.getIsoncyel().equals("1")){

                boolean isOncyel = true;

                    for(String key : week.keySet()){
                      String  value = (String) week.get(key);
                      if(value.equals("1")){
                          isOncyel = false;
                      }
                    }

                    if(isOncyel){
                        json.put("code", "1");
                        json.put("msg", "当前PM未设置工作日,请勾选！");
                        return json.toJSONString();
                    }




                Date exentDate = CommonService.getActualWeekday(week,nextDate,isBefore);
                endExentDate = exentDate;


            }

            // 是否根据实际生成时间更新下次到期日
            boolean isActualNextDate = false;
            Date ActualNextDate = nextDate;
            if(blpm.getIsskipweek().equals("1")){
                isActualNextDate = true;
            }

            if (isActualNextDate) {
                ActualNextDate = endExentDate;
            }

            if(endExentDate.before(sysDate)){


                upDateNextDate = getNextexDate(ActualNextDate,blpm.getFrequency(),blpm.getFrequencyunit());



                // 获取下一个工单编码
                MaxWonum = quryMaxWonum("PM工单","JH-PM-");

                BlWorkorder.setStatus("草稿");
                BlWorkorder.setUdwotype("PM工单");
                BlWorkorder.setWonum(MaxWonum);
                BlWorkorder.setFixplannum(blpm.getInspectionplan());
                BlWorkorder.setFixplandesc(blpm.getInspectionplandesc());
                BlWorkorder.setInspareacode(blpm.getLinerepair());
                BlWorkorder.setInspareadesc(blpm.getLinerepairdesc());
                BlWorkorder.setAssetnum(blpm.getAssetnum());
                BlWorkorder.setAssetdesc(blpm.getAssetdesc());
                BlWorkorder.setLocation(blpm.getLocation());
                BlWorkorder.setLocationdesc(blpm.getLocationdesc());
                BlWorkorder.setPlannum(blpm.getPmnum());
                BlWorkorder.setPlandescription(blpm.getDescription());
                BlWorkorder.setOrgcode(blpm.getOrgcode());
                BlWorkorder.setSitecode(blpm.getSitecode());
                BlWorkorder.setDeptcode(blpm.getDeptcode());
                BlWorkorder.setMaintenanceprincipal(blpm.getPerson());
                BlWorkorder.setWxfzrname(blpm.getFzrdesc());
                BlWorkorder.setClasscode(blpm.getClasscode());
                BlWorkorder.setClassdesc(blpm.getClassdesc());

                // 如果没有选择检修路线 需要将 作业标准写入工单
                String jxlx = blpm.getLinerepair();
                if(jxlx.equals("") || jxlx.equals("null") || jxlx==null){
                    genTaskByInsaenum(MaxWonum,blpm.getInspectionplan());
                }




                PmDao.insertWorkorderMain(MaxWonum,blpm.getDescription(),"PM工单",BlWorkorder);



                // 获取巡检区域的的位置列表  并插入到工单 位置列表中

                //getRouteGenWorkorder(RouteNum,String MaxWonum,String woDesc,String insaenum)

                getRouteGenWorkorder(blpm.getLinerepair(),MaxWonum,blpm.getDescription(),blpm.getInspectionplan(),blpm);




                /*blInspectlocation = quryLocationList(blpm.getLinerepair());
                for (BlInsparealocation inspectlocation : blInspectlocation) {
                    insertWoLocation(MaxWonum,inspectlocation.getSeat(),inspectlocation.getLocaEnityDescription());

                }
                BlInspectasset = queryAssetList(blpm.getLinerepair());
                for (BlInsparealine blInspectasset : BlInspectasset) {
                    insertWoAsset(MaxWonum,blInspectasset.getInsaeassetnum(),blInspectasset.getAssetEnityDescription());

                }

                String wonum = MaxWonum;
                String insaenum = blpm.getInspectionplan();

                String getInfosSql ="select * from bl_jobtask where jpnum ='"+insaenum+"'";
                List<Map<String, Object>> getTaskLists = handlerService.findBySql(getInfosSql);

                String insertPmTaskSql = "";

                for (Map<String, Object> taskList : getTaskLists) {
                    insertPmTaskSql = "insert into bl_workordertask(inspectionassetnum,inspectioncontent,wonum)values ('"+taskList.get("step")+"','"+taskList.get("workmethod")+"','"+wonum+"')";
                    handlerService.updateBySql(insertPmTaskSql);

                }

                String getWpmaterialSql ="select * from bl_wpmaterial where JOBPLANID ='"+insaenum+"'";
                List<Map<String, Object>> getWpmaterialLists = handlerService.findBySql(getWpmaterialSql);
                log.info("====================="+getWpmaterialLists.size());
                String insertPmwpmaterialSql = "";
                for (Map<String, Object> wpmaterialList : getWpmaterialLists) {
                    insertPmwpmaterialSql = "insert into bl_wpmaterial(itemnum,materialEnity_DESCRIPTION,itemqty,wonum)values ('"+wpmaterialList.get("ITEMNUM")+"','"+wpmaterialList.get("DESCRIPTION")+"',"+wpmaterialList.get("ITEMQTY")+",'"+wonum+"')";



                    handlerService.updateBySql(insertPmwpmaterialSql);
                }
                String getWplaborSql ="select * from bl_wplabor where JOBPLANID ='"+insaenum+"'";
                List<Map<String, Object>> getWplaborLists = handlerService.findBySql(getWplaborSql);
                String insertPmWplaborSql = "";
                for (Map<String, Object> WplaborList : getWplaborLists) {
                    insertPmWplaborSql = "insert into bl_wplabor(LABORCODE,planUserEnity_DISPLAYNAME,craftdesc,wonum)values('"+WplaborList.get("LABORCODE")+"','"+WplaborList.get("planUserEnity_DISPLAYNAME")+"','"+WplaborList.get("craftdesc")+"','"+wonum+"')";
                    handlerService.updateBySql(insertPmWplaborSql);
                }
*/


                //更新下次执行时间
                updateNextTime((int) blpm.getId(),upDateNextDate, sdf.format(new Date()));
            }else{
                json.put("code", "1");
                json.put("msg", "当前PM未在活动范围内！");
                return json.toJSONString();
            }

        json.put("code", "0");
        json.put("msg", "PM工单创建成功！");


        return json.toJSONString();
    }


}
